package com.example.testdownload;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.entity.mime.MultipartEntity;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.coe3.data.DataStorage;
import com.coe3.data.Information;
import com.coe3.datahandler.BaseActivity;
import com.coe3.datahandler.HttpConnection;
import com.coe3.datahandler.ParserXMLHandler;
import com.coe3.datahandler.ParserXMLHandler.ElementData;
import com.jotabout.zipdownloader.util.DecompressZip;
import com.jotabout.zipdownloader.util.DownloadFile;
import com.jotabout.zipdownloader.util.ExternalStorage;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.pm.PackageInfo;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends BaseActivity {

	public static final String KEY_PATH = "KEY_PATH";
	public static final String KEY_PACKAGE = "KEY_PACKAGE";
	public static final String KEY_URL_DOWNLOAD = "KEY_URL_DOWNLOAD";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//		new AppDownloadAsync( this ).execute( "http://www.nationmultimedia.com/new/rss/ipad_v2/offline/2012-02-21.zip" );
//		loadData();
		
		findViewById(R.id.btn_download).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//new AppDownloadAsync( MainActivity.this ).execute( "http://www.nationmultimedia.com/new/rss/ipad_v2/offline/2012-02-21.zip" );
				loadData() ;
//				new DownloadTask().execute( "http://www.nationmultimedia.com/new/rss/ipad_v2/offline/2012-02-21.zip" );
			}
		});
	}
	
	public void loadData() {
		String url = "http://www.nationmultimedia.com/new/rss/ipad_v2/ipad_vdo.xml";
	    
		Log.e("max", "MainActivity======loadData()");
	    startConnection( url, "", HttpConnection.GET, -1, null );
	    
	    
	    
	}
	
	static private final int AFTER_INSTALL_PACKAGE = 0;
	
	private static String mPackageInstalledName = null;

	public void onDownloadDidFinish(BaseActivity activity, String filepath ) {

		try {
			String zipFilename = AppDownloadAsync.getExternalCacheDir(activity) + "xxx"; 
			String unzipLocation = AppDownloadAsync.getExternalCacheDir(activity) + "unzipped"; 

			new DecompressAsync(this, zipFilename, unzipLocation).execute(null, null, null);
			
		} catch( Exception e ) {
			activity.showAlertBox("Attention", "There is no network connection right now. Please try again later.");
		}
	}
	
	
	public void setNews(Vector<NewData> listNews) {
		Log.e("max", "MainActivity==========setNews(Vector<NewData> listNews)");
		for (NewData newData : listNews) {
			Information.logDEBUG("title: " + newData.title);
			Information.logDEBUG("description: " + newData.description);
			Information.logDEBUG("enclosure_url: " + newData.enclosure_url);
			Information.logDEBUG("enclosure_type: " + newData.enclosure_type);
			Information.logDEBUG("video: " + newData.video);
		}
		
		
	}
	
	@SuppressLint("HandlerLeak")
	public void startConnection( String url, String data , int method, final int handlerType, final MultipartEntity entity ) {
		Log.e("max", "MainActivity==========startConnection");
		Log.e("chud", "url: " + url);
		Log.e("chud", "data: " + data);
		
		Handler handler = new Handler() {
			@SuppressWarnings("deprecation")
			public void handleMessage(Message message) {
				switch ( message.what ) {
				case HttpConnection.DID_START:
						showDialog( DIALOG_CONNECTION_START );
					break;
				
				case HttpConnection.DID_SUCCEED:
					try {
						Log.e("chud", "(String)message.obj: " + (String)message.obj);
						startParseXMLResponse( (String)message.obj, handlerType );
					} catch ( Exception e ) {
						Log.e( "Connection Exception", "XML Pasing Excpetion : " + e );
		        		didFinishParsing();
					}
					
					break;
				
				case HttpConnection.DID_ERROR:
					Log.e( "Connection Error", "HTTP Connection did error : " + message.obj );
	        		showAlertBox( "Connection Error!!!", "Please try again." );
	        		didFinishParsing();
					break;
				}	
			}
		};

		HttpConnection connection = new HttpConnection(handler);
		if( entity != null )
			connection.setMultipartEntity( entity );
		connection.create(method, url, data);
	}
	
	public void startParseXMLResponse( String response, int handlerType ) throws SAXException, ParserConfigurationException, IOException {
	
		Log.e("max", "MainActivity==========startParseXMLResponse");
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		
		ParserXMLHandler parser = null;
		Handler handler = handlerInformation(handlerType);
		parser = new ParserXMLHandler( this, handler );
		
		StringReader sr = new StringReader(response);
		InputSource is = new InputSource(sr);
		
		xr.setContentHandler(parser);
		xr.parse(is);
	}
	
	private static Vector<NewData> mListNews = new Vector<NewData>();
	private NewData mItem = null;
	
	@SuppressLint("HandlerLeak")
	public Handler handlerInformation(final int handlerType) {
		
		Log.e("max", "MainActivity==========handlerInformation");
		
		Handler mHandler = new Handler() {
			public void handleMessage( Message message ) {
				ElementData data = ( ElementData )message.obj;
				switch( message.what ) {
					case ParserXMLHandler.START_DOCUMENT:
						
						mListNews.removeAllElements();
						
						break;
						
					case ParserXMLHandler.DID_START_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mItem = new NewData();
						}//end if
						
						if( data.attributes.containsKey(NewData.TAG_ENCLOSURE_URL) ) 
						{
							mItem.enclosure_url = Information.setData(data.attributes.get(NewData.TAG_ENCLOSURE_URL), Information.STR_EMPTY);
						}//end if
						
						if( data.attributes.containsKey(NewData.TAG_ENCLOSURE_TYPE) ) {
							mItem.enclosure_type = Information.setData(data.attributes.get(NewData.TAG_ENCLOSURE_TYPE), Information.STR_EMPTY);
						}//end if
						
						
						
						break;
						
					case ParserXMLHandler.DID_FINISH_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_TITLE) ) 
						{
							mItem.title = Information.setData(data.value, Information.STR_EMPTY);
						} 
						else if( data.name.equalsIgnoreCase(NewData.TAG_DESCRIPTION) ) 
						{
							mItem.description = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(NewData.TAG_VIDEO) ) 
						{
							mItem.video = Information.setData(data.value, Information.STR_EMPTY);
						}
						else if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mListNews.add(mItem);
							mItem = null;
						}//end if
						
						break;
						
					case ParserXMLHandler.END_DOCUMENT:
						
						setNews(mListNews);
						
						break;
				}
			}
		};
			
		return mHandler;
	}
	
	public void onActivityResult(BaseActivity activity, int requestCode) {
		if( requestCode == AFTER_INSTALL_PACKAGE ) {
        	boolean found = false;
        	
        	String path = DataStorage.getData(activity, KEY_PATH, null);
			Log.d("chud", "Data_Storage path: " + path);
			if(path != null)
			{
				Log.d("chud", "getFileStreamPath( path ).delete(): " + activity.getFileStreamPath( path ).delete());
			}//end if
        	
        	Log.d( "chud", "found : " + found );
        	Log.d( "chud", "mPackageInstalledName : " + mPackageInstalledName );
        	
        	String package_install = DataStorage.getData(activity, KEY_PACKAGE, null);
        	
        	Log.d( "chud", "package_install : " + package_install );
        	
            List<PackageInfo> packs = activity.getPackageManager().getInstalledPackages(0);
            for( int i = 0; i < packs.size(); i++ ) {
                PackageInfo p = packs.get(i);
                Log.d( "chud", "PackageInfo name : " + p.packageName );
                if( p.packageName.equals( mPackageInstalledName ) ) {
                	found = true;
                	break;
                }//end if
                
                if( p.packageName.equals( package_install ) ) {
                	found = true;
                	break;
                }//end if
            }//end for
        }//end if
	}
	
	//////////////////////////////////////////////////////////////////////////
	// State
	//////////////////////////////////////////////////////////////////////////
	
	protected ProgressDialog mProgressDialog;
	
	//////////////////////////////////////////////////////////////////////////
	// Activity Lifecycle
	//////////////////////////////////////////////////////////////////////////
	
	//////////////////////////////////////////////////////////////////////////
	// Event handlers
	//////////////////////////////////////////////////////////////////////////
	
	/**
	* Invoked when user presses "Start download" button.
	*/
	public void startDownload( View v ) {
//		String url = ((TextView) findViewById(R.id.url_field)).getText().toString();
//		new DownloadTask().execute( url );
	}
	
	//////////////////////////////////////////////////////////////////////////
	// Background Task
	//////////////////////////////////////////////////////////////////////////
	
	/**
	* Background task to download and unpack .zip file in background.
	*/
	private class DownloadTask extends AsyncTask<String,Void,Exception> {
	
		@Override
		protected void onPreExecute() {
		showProgress();
		}
		
		@Override
		protected Exception doInBackground(String... params) {
		String url = (String) params[0];
		
		try {
			downloadAllAssets(url);
		} catch ( Exception e ) { return e; }
		
		return null;
		}
		
		@Override
		protected void onPostExecute(Exception result) {
			dismissProgress();
			if ( result == null ) { return; }
			// something went wrong, post a message to user - you could use a dialog here or whatever
			Toast.makeText(MainActivity.this, result.getLocalizedMessage(), Toast.LENGTH_LONG ).show();
		}
	}
	
	//////////////////////////////////////////////////////////////////////////
	// Progress Dialog
	//////////////////////////////////////////////////////////////////////////
	
	protected void showProgress( ) {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setTitle( R.string.progress_title );
		mProgressDialog.setMessage( getString(R.string.progress_detail) );
		mProgressDialog.setIndeterminate( true );
		mProgressDialog.setCancelable( false );
		mProgressDialog.show();
	}
	
	protected void dismissProgress() {
		// You can't be too careful.
		if (mProgressDialog != null && mProgressDialog.isShowing() && mProgressDialog.getWindow() != null) {
			try {
				mProgressDialog.dismiss();
			} catch ( IllegalArgumentException ignore ) { ; }
		}
		mProgressDialog = null;
	}
	
	//////////////////////////////////////////////////////////////////////////
	// File Download
	//////////////////////////////////////////////////////////////////////////
	
	/**
	* Download .zip file specified by url, then unzip it to a folder in external storage.
	*
	* @param url
	*/
	private void downloadAllAssets( String url ) {
		// Temp folder for holding asset during download
		File zipDir =  ExternalStorage.getSDCacheDir(this, "tmp");
		// File path to store .zip file before unzipping
		File zipFile = new File( zipDir.getPath() + "/temp.zip" );
		// Folder to hold unzipped output
		File outputDir = ExternalStorage.getSDCacheDir( this, "unzipped" );
		
		Information.logDEBUG("getPath: " + zipDir.getPath());
		
		try {
			DownloadFile.download( url, zipFile, zipDir );
			unzipFile( zipFile, outputDir );
		} finally {
			zipFile.delete();
		}
	}
	
	//////////////////////////////////////////////////////////////////////////
	// Zip Extraction
	//////////////////////////////////////////////////////////////////////////
	
	/**
	* Unpack .zip file.
	* 
	* @param zipFile
	* @param destination
	*/
	protected void unzipFile( File zipFile, File destination ) {
		DecompressZip decomp = new DecompressZip( zipFile.getPath(), 
		destination.getPath() + File.separator );
		decomp.unzip();
	}
}
